<template>
    <div class='article-add'>
        <div class="containner">
            <div class="title">
                发布视频
            </div>
            <el-form style="display: flex;" :rules="rules" ref="ruleForm" label-position="left" label-width="80px"
                     :model="article">
                <div class="article-left">
                    <el-row :gutter="20">
                        <el-col :span="16">
                            <el-form-item label="标题" prop="title">
                                <el-input v-model="article.title"></el-input>
                            </el-form-item>
                            <el-form-item label="简介" prop="summary">
                                <el-input v-model="article.summary"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="封面图" prop="">
                                <el-upload class="avatar-uploader" :show-file-list="false" ref="upload" name="filedatas"
                                           :action="uploadPictureHost" :before-upload="uploadBefore"
                                           :http-request="uploadSectionFile" multiple>
                                    <img v-if="article.avatar" style="width: 100%;height: 100%;" :src="article.avatar"
                                         class="imgAvatar" />
                                    <i v-else class="el-icon-plus avatar-img-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="内容" prop="contentMd">
                        <!--mavon-editor的主体-->
                        <mavon-editor
                                placeholder="输入内容..."
                                ref="md"
                                v-model="article.contentMd"
                                @imgDel="imgDel" @change="" @imgAdd="imgAdd"
                                style="height: 500px"
                                :xssOptions="{whiteList: {iframe: ['src', 'height', 'width'],div: ['style', 'height', 'width', 'align'],},}"
                        >

                            <!-- 引用视频链接的自定义按钮 -->
                            <template v-slot:left-toolbar-after>
                                <!--点击按钮触发的事件是打开表单对话框-->
                                <el-button type="text" @click="dialogFormVisible=true" aria-hidden="true" class="op-icon fa" title="插入视频地址">
                                    <i class="el-icon-video-camera-solid" style="margin-right: 10px;background-color: #eeff02;width: 20px;height: 20px"/>   点击插入视频地址
                                </el-button>
                            </template>
                        </mavon-editor>
                        <!--<mavon-editor placeholder="输入内容..." style="height: 500px" ref=md v-model="article.contentMd"
                                      @imgDel="imgDel" @change="" @imgAdd="imgAdd" />-->
                    </el-form-item>
                </div>
                <div class="article-right">
                    <div class="top">
                        <el-form-item label="标签" prop="tagList">
                            <el-select v-model="article.tagList" :multiple-limit="3" multiple placeholder="请选择标签">
                                <el-option v-for="item in tagList" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="分类" prop="categoryId">
                            <el-select v-model="article.categoryId" placeholder="请选择分类">
                                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="创作类型" prop="isOriginal">
                           <!-- <el-radio v-model="article.isOriginal" :label="1">原创</el-radio>-->
                            <el-radio v-model="article.isOriginal" :label="0" border>转载</el-radio>
                        </el-form-item>
                        <el-form-item v-if="article.isOriginal == 0" label="视频地址" prop="originalUrl">
                            <el-input v-model="article.originalUrl"></el-input>
                        </el-form-item>
                    </div>

                    <div class="bottom">
                        <div class="btn-tips">Are you ready</div>
                        <button v-if="$store.state.userInfo" type="button" class="btnDraft" @click="submit">
                            <i class="el-icon-orange"></i> 保存草稿
                        </button>
                        <button v-if="$store.state.userInfo" type="button" class="btnSubmit" @click="submit">
                            <i class="el-icon-circle-check"></i> 提交审核
                        </button>
                        <span v-else class="noBtn">
                            暂无发布权限,请先<a @click="$store.state.loginFlag = true">登录</a>
                        </span>
                    </div>
                </div>
            </el-form>
        </div>
        <!-- 插入视频链接的dialog提示框，表单对话框 -->
        <el-dialog title="插入视频资源" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="视频链接" :label-width="formLabelWidth">
                    <el-input v-model="form.link" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="链接类型" :label-width="formLabelWidth">
                    <el-select v-model="form.region" placeholder="请选择链接类型">
                        <el-option label="iframe标签" value="iframe"></el-option>
                        <el-option label="url链接" value="url"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <!--单机确定按钮后触发 videoLink事件函数，开始格式化链接格式并插入到文本域-->
                <el-button type="primary" @click="videoLink">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import { upload, featchCategory, insertArticle, getMyArticleInfo, fetchTagList } from '@/api'
    export default {
        data() {
            return {
                uploadPictureHost: process.env.VUE_APP_BASE_API + "/file/upload",
                article: {isOriginal:0},
                dialogFormVisible:false,
                formLabelWidth: '120px',	// 设定表单对话框内表单是宽度
                form: {		// 表单对话框内表单的数据
                    link: '',
                    region: ''
                },
                categoryList: [],
                loading: [],
                img: process.env.VUE_APP_IMG_API,
                articleId: this.$route.query.id,
                tagList: [],
                rules: {
                    title: [
                        { required: true, message: '请输入名称', trigger: 'blur' },
                    ],
                    avatar: [
                        { required: true, message: '请上传封面', trigger: 'change' },
                    ],
                    summary: [
                        { required: true, message: '请输入简介', trigger: 'blur' },
                    ],
                    tagList: [
                        { required: true, message: '请选择标签', trigger: 'blur' },
                    ],
                    categoryId: [
                        { required: true, message: '请选择分类', trigger: 'blur' },
                    ],
                    isOriginal: [
                        { required: true, message: '请选择创作类型', trigger: 'blur' },
                    ],
                    originalUrl: [
                        { required: true, message: '请输入转载地址', trigger: 'blur' },
                    ],
                    contentMd: [
                        { required: true, message: '请输入内容', trigger: 'blur' },
                    ],
                }
            };
        },
        created() {
            if (this.articleId) {
                getMyArticleInfo(this.articleId).then(res => {
                    this.article = res.data
                })
            }
            featchCategory().then(res => {
                this.categoryList = res.data
            })
            fetchTagList().then(res => {
                this.tagList = res.data
            })
        },
        methods: {
            // 格式化视频链接并插入到文本域的函数
            videoLink() {
                // 准备链接模板
                let linkFrame = '';
                let linkFrameStart = "<div align=center width=100%><iframe style='border-radius:10px; margin-top: 30px;width: 765px;height: 430px;' src='"
                let linkFrameEnd = "'scrolling='no' frameborder=0 sandbox='allow-top-navigation allow-same-origin allow-forms allow-scripts' allowfullscreen='allowfullscreen'></iframe></div>"
                // 创建一个div盒子，为提取src做准备
                var box = document.createElement("div");
                // 将原始链接插入到盒子中
                box.innerHTML=this.form.link;
                // 判断不同的视频原链接类型
                if(this.form.region == "url"){
                    linkFrame = linkFrameStart + this.form.link + linkFrameEnd;
                }else if(this.form.region == "iframe" && box.getElementsByTagName("iframe").length > 0) {
                    // 从iframe标签中提取src属性
                    linkFrame = linkFrameStart + box.getElementsByTagName("iframe")[0].getAttribute("src")+"&as_wide=1&high_quality=1&danmaku=0" + linkFrameEnd;
                }else {
                    // 原始链接格式错误时弹出错误提示
                    this.dialogFormVisible=false;
                    this.dialogVisible=true;
                }
                // 复原表单文本框内容
                this.form.link = '';
                this.form.region = '';

                // 获取文本域中当前光标起始位置、结束位置以及滚动条位置（滚动条位置我认为没有必要，如有需要可以自己取消注释）
                let textarea = document.getElementsByClassName("auto-textarea-input")[0];
                let posStart = textarea.selectionStart;
                let posEnd = textarea.selectionEnd;
                // let posScroll = document.getElementsByClassName("v-note-edit")[0].scrollTop;
                // 获取文本域中未选中的的前半部分和后半部分，以被选中内容起始和结束位置做分割点
                let subStart = this.$refs.md.d_value.substring(0, posStart);
                let subEnd = this.$refs.md.d_value.substring(posEnd, this.$refs.md.d_value.length);
                // 拼接并替换文本域内容
                //this.$refs.md.d_value = subStart + '\n' + linkFrame + '\n' + subEnd;
                // document.getElementsByClassName("v-note-edit")[0].scrollTop = posScroll;
                 this.article.content = linkFrame;
                 this.article.contentType= 1;
                // 关闭对话框
                this.dialogFormVisible = false;
            },
            imgAdd: function (pos, $file) {
                var formdata = new FormData();
                formdata.append('multipartFile', $file);
                upload(formdata).then(res => {
                    this.$refs.md.$img2Url(pos, res.data);
                }).catch(err => {
                    console.log(err)
                })
            },
            imgDel: function (filename) {
                delBatchFile(filename[0].split(this.img)[1])
            },
            submit() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        if (!this.article.contentMd) {
                            this.$notify({
                                title: '失败',
                                message: '请编写内容！',
                                type: 'error'
                            });
                            return;
                        }
                        debugger
                        insertArticle(this.article).then(res => {
                            this.$notify({
                                title: '成功',
                                message: '提交成功，请耐心等待审核',
                                type: 'success'
                            });
                            this.$router.push({ path: "/user" })
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleUploadImage(event, insertImage, files) {
                const file = files[0]
                // FormData 对象
                var formData = new FormData()
                // 文件对象
                formData.append('multipartFile', file)
                upload(formData).then(res => {
                    insertImage({
                        url: res.data,
                        desc: file.name,
                        width: '100%',
                        height: '300px',
                    });
                })

            },
            uploadBefore: function () {
                //this.openLoading()
            },
            uploadSectionFile: function (param) {
                this.files = param.file
                // FormData 对象
                var formData = new FormData()
                // 文件对象
                formData.append('multipartFile', this.files)
                upload(formData).then(res => {
                    this.article.avatar = res.data
                    this.loading.close()
                }).catch(error => {
                    console.log("y有错进来啦！！！！！")
                    this.loading.close()
                })
            },
            // 打开加载层
            openLoading: function () {
                this.loading = this.$loading({
                    lock: true,
                    text: "正在加载中~",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)"
                });
            },

        }
    };
</script>
<style lang="scss" scoped>
    .article-add {
        display: flex;
        justify-content: center;

        @media screen and (max-width: 1118px) {
            padding: 0 5px;

            .containner {
                width: 100%;
                margin-top: 80px;

            }
        }

        @media screen and (min-width: 1119px) {
            .containner {
                width: 80%;
                margin-top: 80px;
            }
        }

        .containner {
            padding: 10px;

            /deep/ .article-left input {
                border-top: none !important;
                border-left: none !important;
                border-right: none !important;

                &:hover {
                    border-color: var(--theme-color) !important;
                }
            }

            .title {
                margin-bottom: 15px;
                color: var(--text-color);
            }

            .article-left,
            .article-right .top,
            .bottom {
                border-radius: 5px;
                padding: 10px;
            }

            .article-left {
                background-color: var(--background-color);
                margin-right: 20px;
                width: 100%;
                max-width: 80%;

                .el-textarea {
                    width: 92%;
                }

                /deep/ .contentInput textarea {
                    resize: none;
                    background-color: var(--background-color);
                }
            }

            .article-right {
                width: 35%;
                height: 100%;
                display: flex;
                flex-direction: column;

                .top,
                .bottom {
                    background-color: var(--background-color);
                }

                .bottom {
                    margin-top: 20px;
                    text-align: center;

                    .btn-tips {
                        color: #b5b5b5;
                        font-size: 0.75rem;
                        margin-bottom: 1rem;

                        &::before {
                            content: "";
                            display: inline-block;
                            background-color: #d8d8d8;
                            width: 60px;
                            height: 1px;
                            margin: 0 12px;
                            vertical-align: middle;
                        }

                        &::after {
                            content: "";
                            display: inline-block;
                            background-color: #d8d8d8;
                            width: 60px;
                            height: 1px;
                            margin: 0 12px;
                            vertical-align: middle;
                        }
                    }

                    .btnDraft,
                    .btnSubmit {
                        padding: 10px;
                        width: 50%;
                        border: none;
                        margin: 0 auto;
                        color: #fff;
                        font-weight: 700;

                        &:hover {
                            color: var(--theme-color);
                        }
                    }

                    .btnDraft {
                        border-top-left-radius: 5px;
                        border-bottom-left-radius: 5px;
                        background: linear-gradient(135deg, #60e464 10%, #5cb85b 100%);
                    }

                    .btnSubmit {
                        border-top-right-radius: 5px;
                        border-bottom-right-radius: 5px;
                        background: linear-gradient(135deg, #59c3fb 10%, #268df7 100%);
                    }

                    .noBtn {
                        color: var(--text-color);

                        a {
                            color: var(--theme-color);
                        }
                    }
                }

            }

        }
    }

    /deep/ .avatar-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: url(http://img.aijsq.com/link.cur), pointer;
        position: relative;
        overflow: hidden;
        width: 200px;
        height: 100px;
        text-align: center;
    }

    /deep/ .el-upload {
        width: 100%;
        height: 100%;
    }

    /deep/ .avatar-uploader:hover {
        border-color: #409EFF;
    }

    /deep/ .el-icon-plus {
        font-size: 28px;
        color: #8c939d;
        line-height: 100px;
    }

    /deep/ .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
